/**
 * @JsonHttpEndpoint.java  COPYRIGHT xiaojian
 * 
 * Created on 2016年7月20日 下午6:26:53
 */
package xj.toolkit.netty.transport.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import xj.toolkit.bean.json.JSONSignal;
import xj.toolkit.bean.json.annotation.JSONMessage;
import xj.toolkit.netty.util.NettyConstants;
import xj.toolkit.util.ByteUtils;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class JsonHttpEndpoint extends HttpEndpoint {

	private static final Logger logger = LoggerFactory.getLogger(JsonHttpEndpoint.class);

	@Override
	public byte[] makeHttpBody(Object requestBean, Object response) {
		String jsonStr = JSON.toJSONString(response);

		// -- 使用jsonp数据格式。
		if (requestBean instanceof JSONSignal) {
			JSONSignal jsonSinal = (JSONSignal) requestBean;
			if (jsonSinal.isJsonP()) {
				jsonStr = "xtCallback(" + jsonStr + ")";
			}
		}

		byte[] bytes = jsonStr.getBytes();

		if (logger.isDebugEnabled()) {
			logger.debug("sendback bean as Hex \r\n{} ", ByteUtils.bytesAsTLVHexString(bytes, 8096));
		}

		return bytes;
	}

	@Override
	protected void beforeSend(HttpRequest httpRequest, FullHttpResponse response, Object responseBean) {
		response.headers().add(HttpHeaders.Names.CONTENT_TYPE, NettyConstants.JSON_TYPE);
		// -- MsgCode
		JSONMessage jsonMessage = responseBean.getClass().getAnnotation(JSONMessage.class);
		if (jsonMessage != null) {
			response.headers().add(NettyConstants.HEADER_MESSAGE_CODE, jsonMessage.messageCode());
		}
	}

}